<?php

namespace App\Http\Controllers\Bus;

use App\Http\Controllers\Controller;
use App\Models\Bus\BusDistribution;
use App\Models\Bus\BusTeamLine;
use App\Models\Dict;
use Illuminate\Http\Request;

class BusDistributionController extends Controller
{
    public function busDistributionList(Request $request)
    {
        $params = $countParams = $request->all();
        unset($countParams['pageNumber'], $countParams['pageSize']);

        $data = $this->getBusDistributionList($params)
            ->orderByDesc('date')
            ->orderBy('line')
            ->get()
            ->toArray();
        if ($data) {
            $data = $this->transData($data);
        }
        $dataCount = $this->getBusDistributionList($countParams)->count();

        return response()->formatJson(['busDistributionRecord' => $data, 'count' => $dataCount]);
    }

    public function getBusDistributionList($params): \Illuminate\Database\Eloquent\Builder
    {
        $query = BusDistribution::query();

        if (isset($params['pageNumber'], $params['pageSize'])) {
            $query
                ->limit($params['pageSize'])
                ->offset(($params['pageNumber'] - 1) * $params['pageSize']);
        }

        return $query;
    }

    /**
     * 数据转化
     *
     * @param  array  $data
     *
     * @return array
     */
    public function transData(array $data): array
    {
        foreach ($data as $key => $item) {
            $data[$key]['lineTitle'] = $item['line'] === 0 ? '停运' : $item['line'].'路';
            $data[$key]['license_plate_num_title'] = '陕G'.$item['license_plate_num'];
        }

        return $data;
    }

    /**
     * 创建车辆信息
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function store(Request $request)
    {
        $params = $request->all();
        $params['license_plate_num'] = str_replace('陕G', '', $params['license_plate_num']);
        $params['end_date'] = '2030-12-31';
        $params['line'] = (int)trim($params['line']);
        $params['team'] = trim($params['team']);

        $lastBus = BusDistribution::query()
            ->where('license_plate_num', $params['license_plate_num'])->orderByDesc('date')->first();
        $busDistribution = new BusDistribution($params);
        $result = $busDistribution->save();

        // 找到最后一辆车，把end_date改为新版本的前一天
        if ($lastBus) {
            $lastBus->update(['end_date' => date('Y-m-d', strtotime('-1 days', strtotime($params['date'])))]);
        }

        $message = $result ? '添加成功' : '添加失败';

        return response()->formatJson($result, $message);
    }

    /**
     * 修改文章
     *
     * @param  Request  $request
     * @param           $id
     *
     * @return mixed
     */
    public function update(Request $request, $id)
    {
        $params = $request->all();
        $params['license_plate_num'] = str_replace('陕G', '', $params['license_plate_num']);

        $params['line'] = (int)trim($params['line']);
        $params['team'] = trim($params['team']);
        $busDistribution = BusDistribution::query()->find($id);

        $result = $busDistribution->update($params);

        $message = $result ? '修改成功' : '修改失败';

        return response()->formatJson($result, $message);
    }

    /**
     * 删除车辆信息
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function destroy(Request $request)
    {
        $result = false;
        if ($request->has('ids')) {
            $ids = explode(',', $request['ids']);
            $busDistributionCount = BusDistribution::destroy($ids);
            $result = $busDistributionCount !== 0;
        }

        $message = $result ? '删除成功' : '删除失败';

        return response()->formatJson($result, $message);
    }
    /**
     * 2021-04-13 新增
     * 获取所有线路数组
     *
     * @return void
     */
    public function getLines()
    {
        $lines = BusDistribution::query()->groupBy('line')->orderBy('line')->pluck('line');
        $result = [];
        foreach ($lines as $key=> $value) {
            if ($value==0) {
                $result[$key]['label']='停运';
                $result[$key]['value']=$value;
            }else{
                $result[$key]['label']=$value;
                $result[$key]['value']=$value;
            }
        }
        return  response()->formatJson($result);
    }
    /**
     * 获取所有车队数组
     *
     * @return void
     */
    public function getTeamlist()
    {
        $teamList = Dict::getOptionsByName('车队类型');
        $result = [];
        foreach ($teamList as $k => $v) {
            $result[$k]['label'] = $v['title'];
            $result[$k]['value'] = $v['value'];
        }
        return response()->formatJson($result);
    }
}
